package main

import (
	"fmt"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

var (
	DataBase = "test"
	DBaddr   = "192.168.2.11:3306"
	user     = "root"
	passwd   = "root"
)

type UserInfo struct {
	Id      int //字段要大写首字母
	Name    string
	Kind    string
	Describ string
}

func initdb() *gorm.DB {
	// DSN:Data Source Name
	dsn := user + ":" + passwd + "@tcp(" + DBaddr + ")/" + DataBase + "?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open("mysql", dsn)
	if err != nil {
		panic(err)
	}
    //创建表 自动迁移(根据结构体创建表)
	db.AutoMigrate(&UserInfo{})
	fmt.Println("初始化数据库成功......")
	return db
}

func main() {
	//初始化数据库
	db := initdb()
	defer db.Close()
	//插入数据
	db1 := UserInfo{Id: 1, Name: "😃", Kind: "表情", Describ: "快乐"}
	db.Create(&db1)
	//查询数据
	var db2 UserInfo
	db.First(&db2)
	fmt.Println(&db2)
	db.First(&db2, "id=2")
	fmt.Println(&db2)
	//改
	db.Model(db2).Update("name", "标签")
	//删
	//db.Delete(&db2)
}